package ua.yandex.skipass;

import java.util.Calendar;
import java.util.Date;

/**
 *
 * @author Кирилл
 */

public class SkiPassWeekendRacesLimitedCard extends SkiPassCard {
    
    private static final int WEEKAND_IN_WEEK = 2;
    
    private int numberOfRemainingRaces;
    
    SkiPassWeekendRacesLimitedCard(Date activationDate, Date expirationDate,  
                                   int id, SkiPassRaces race) {
        super(activationDate, expirationDate, id,
                SkiPassType.WEEKEND_RACES_LIMITED);
        if (expirationDate.getTime() < activationDate.getTime()) {
            throw new OutOfBoundException(
                      "This card will be activated after it has expired");
        }
        if (expirationDate.getTime() > 
            getTheEndOfCurrentWeekend(activationDate).getTime()) {
            throw new OutOfBoundException(
                    "Duration of required season ticket exceed max possible");
        }
        numberOfRemainingRaces = race.getNumberOfRaces();
    }
    
    SkiPassWeekendRacesLimitedCard(Date activationDate, 
                                   int id, SkiPassRaces race) {
        super(activationDate, getTheEndOfCurrentWeekend(activationDate), id,
                              SkiPassType.WEEKEND_RACES_LIMITED);
        numberOfRemainingRaces = race.getNumberOfRaces();
    }

    SkiPassWeekendRacesLimitedCard(int id, SkiPassRaces race) {
        super(new Date(System.currentTimeMillis()), getTheEndOfCurrentWeekend(),
                id, SkiPassType.WEEKEND_RACES_LIMITED);
        numberOfRemainingRaces = race.getNumberOfRaces();
    }
    
    private static Date getTheEndOfCurrentWeekend(Date currentDate) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentDate);
        calendar.add(Calendar.WEEK_OF_MONTH, WEEKAND_IN_WEEK);
        // it needs checking...
        Date expirationDate = calendar.getTime();
        return expirationDate;
    }
    private static Date getTheEndOfCurrentWeekend() {
        return getTheEndOfCurrentWeekend(new Date(System.currentTimeMillis()));
    }
    
    @Override
    public boolean passIsAllowed() {
        if (isBlocked()) {
            return false;
        }
        if (isExpired()) {
            return false;
        }
        if (SkiPassSystem.isWorkday()) {
            return false;
        }
        return numberOfRemainingRaces > 0;
    }
    
    public void decreaseNumberOfRaces() {
        if (numberOfRemainingRaces <= 0) {
            throw new OutOfBoundException("You have no available races");
        }
        numberOfRemainingRaces--;
    }
    
    public int getNumberOfRemainingRaces() {
        return numberOfRemainingRaces;
    }
}
